package pack1;

import java.io.IOException;
import java.util.List;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import swim.entitybeans.Ability;
import swim.sessionbeans.AbilityManagerRemote;

/**
 * Servlet implementation class AddNewAbilityServlet
 */
public class AddNewAbilityServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddNewAbilityServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String name = request.getParameter("abilityname");
		try {
			InitialContext jndiContext = new InitialContext();
			AbilityManagerRemote abilman = (AbilityManagerRemote) jndiContext.lookup("AbilityManager/remote");
			List<Ability> abilities = abilman.listAllAbilities();
			boolean exist = false;
			for (Ability a: abilities) {
				if (a.getName().equalsIgnoreCase(name)) {
					exist = true;
					break;
				}
			}
			if (exist == true) {
				request.getSession().setAttribute("pageMessage", "ERROR: Ability \""+ name.toLowerCase() + "\" already exists");
				request.getSession().setAttribute("pageMessageType", "error");
				response.sendRedirect("./administrationpage.jsp");
			} else {
				boolean result = abilman.addNewAbility(name.toLowerCase());
				if (result == true) {
					request.getSession().setAttribute("pageMessage", "SUCCESS: New ability \""+ name.toLowerCase() + "\" declared");
					request.getSession().setAttribute("pageMessageType", "succes");
					response.sendRedirect("./administrationpage.jsp");
				} else {
					request.getSession().setAttribute("pageMessage", "ERROR: couldn't declare new ability \""+ name.toLowerCase() + "\"");
					request.getSession().setAttribute("pageMessageType", "error");					
					response.sendRedirect("./administrationpage.jsp");
				}
			}
		} catch (NamingException e) {
			e.printStackTrace();
			request.getSession().setAttribute("pageMessage", "ERROR: couldn't declare new ability \""+ name.toLowerCase() + "\"");
			request.getSession().setAttribute("pageMessageType", "error");
			response.sendRedirect("./administrationpage.jsp");
		}
	}

}
